<template>
  <div class="app-container">
    <el-row :gutter="0">
      <!-- 劳务类型菜单 -->
      <el-col :xs="24" :sm="24" :md="3" style="padding:0;margin-right:0;">
        <el-card shadow="never">
          <div
            style="font-weight:bold; margin-bottom:10px; display: flex; align-items: center; justify-content: space-between;">
            <span>劳务类型</span>
            <i v-hasPermi="['cost:materialLedger:typechange']" class="el-icon-plus type-add-icon"
              @click="showAddTypeDialog = true" style="cursor:pointer;"></i>
          </div>
          <el-menu :default-active="activeType" @select="handleTypeSelect">
            <el-menu-item v-for="type in ledgerTypes" :key="type.value" :index="type.value" class="custom-menu-item">
              <div class="item-icon">
                <i :class="type.icon"></i>
              </div>
              <el-tooltip class="item-title-tooltip" effect="dark" :content="type.label" placement="top"
                :disabled="!isTextTruncated(type.label)">
                <span class="item-title">
                  {{ type.label }}
                </span>
              </el-tooltip>
              <i v-hasPermi="['cost:materialLedger:typechange']" class="type-delete-icon el-icon-delete"
                @click.stop="handleDeleteType(type)"></i>
            </el-menu-item>
            <div v-if="ledgerTypes.length === 0" style="padding: 20px; text-align: center; color: #909399;">
              <i class="el-icon-folder-opened" style="font-size: 24px; margin-bottom: 8px;"></i>
              <div>暂无劳务类型</div>
              <div style="font-size: 12px; margin-top: 4px;">点击上方"+"添加劳务类型</div>
            </div>
          </el-menu>
        </el-card>
      </el-col>

      <!-- 右侧主内容 -->
      <el-col :xs="24" :sm="24" :md="21" style="padding-left:0;margin-left:0;">
        <el-card shadow="never" class="main-card">
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="80px">
            <el-form-item label="所属项目" prop="projectId">
              <el-select clearable filterable v-model="queryParams.projectId" placeholder="请选择项目">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="审核状态" prop="auditStatus">
              <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable filterable>
                <el-option v-for="dict in dict.type.review_status" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['cost:prodProjectLabor:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="success" icon="el-icon-upload2" size="mini" @click="handleImport"
                v-hasPermi="['cost:prodProjectLabor:add']">导入</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport"
                v-hasPermi="['cost:prodProjectLabor:export']">导出</el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
          </el-row>

          <div class="color-legend" style="margin-bottom: 10px; font-size: 12px; color: #666;">
            <span style="margin-right: 15px;">
              <span
                style="display: inline-block; width: 16px; height: 16px; background-color: #fff3cd; border: 1px solid #ddd; margin-right: 5px;"></span>
              黄色：录入时间与截至日期相差超过3天且未审核
            </span>
            <span>
              <span
                style="display: inline-block; width: 16px; height: 16px; background-color: #f8d7da; border: 1px solid #ddd; margin-right: 5px;"></span>
              红色：录入时间与截至日期相差超过7天且未审核
            </span>
          </div>

          <el-table v-loading="loading" :data="prodProjectLaborList" @selection-change="handleSelectionChange"
            :row-class-name="rowClassName">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="开始时间" align="center" prop="startDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="截止时间" align="center" prop="endDate" width="100">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="人数" align="center" prop="peopleCount" /> -->
            <el-table-column label="工种" align="center" prop="jobType" />
            <!-- <el-table-column label="含税单价" align="center" prop="taxIncludedPrice" /> -->
            <el-table-column label="含税金额" width="100" align="center" prop="amount" />
            <el-table-column label="不含税金额" width="100" align="center" prop="taxExcludedCost" />
            <el-table-column label="审核状态" width="90" align="center" prop="auditStatus">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.review_status" :value="scope.row.auditStatus" />
              </template>
            </el-table-column>
            <el-table-column label="所属项目" align="center" prop="projectId" width="170">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" :content="getProjectNameById(scope.row.projectId)"
                  placement="top">
                  <span
                    style="max-width: 120px; display: inline-block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: middle;"
                    :title="getProjectNameById(scope.row.projectId)">
                    {{ getProjectNameById(scope.row.projectId) }}
                  </span>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <!-- 审核按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:prodProjectLabor:audit']" size="mini"
                  type="text" icon="el-icon-check" @click="handleAudit(scope.row)">审核</el-button>

                <!-- 取消审核按钮 -->
                <el-button v-else-if="scope.row.auditStatus == 2" v-hasPermi="['cost:prodProjectLabor:unaudit']"
                  size="mini" type="text" icon="el-icon-close" @click="handleCancelAudit(scope.row)">取消审核</el-button>

                <!-- 修改按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:prodProjectLabor:edit']" size="mini"
                  type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>

                <!-- 详情按钮 -->
                <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)">详情</el-button>

                <!-- 删除按钮 -->
                <el-button v-if="scope.row.auditStatus == 1" v-hasPermi="['cost:prodProjectLabor:remove']" size="mini"
                  type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改项目劳务台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <!-- 项目总金额显示区域 -->
      <div class="amount-display-section">
        <div class="amount-display-label">当前类型项目总含税金额：</div>
        <div class="amount-display-content">
          <span v-if="loadingAmount" class="amount-loading">
            <i class="el-icon-loading"></i> 正在获取...
          </span>
          <span v-else class="amount-value">{{ form.projectAmountTotal !== null && form.projectAmountTotal !== undefined
            ?
            form.projectAmountTotal : '选择项目后自动显示' }}</span>
          <span v-if="!loadingAmount && form.projectAmountTotal !== null && form.projectAmountTotal !== undefined"
            class="amount-unit">元</span>
        </div>
      </div>

      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属项目" prop="projectId">
              <el-select v-model="form.projectId" placeholder="请选择项目" style="width: 100%" filterable clearable
                @change="handleProjectChange">
                <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDate">
              <el-date-picker clearable v-model="form.startDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择开始时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="截止时间" prop="endDate">
              <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="请选择截止时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="人数" prop="peopleCount">
              <el-input v-model="form.peopleCount" placeholder="请输入人数" />
            </el-form-item>
          </el-col> -->

          <el-col :span="12">
            <el-form-item label="工种" prop="jobType">
              <el-input v-model="form.jobType" placeholder="请输入工种" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="进项税率" prop="taxRate">
              <el-select v-model="form.taxRate" placeholder="请选择进项税率" filterable style="width: 100%">
                <el-option v-for="dict in dict.type.input_tax" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量单位" prop="unitOfMeasurement">
              <el-input v-model="form.unitOfMeasurement" placeholder="请输入计量单位" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="含税单价" prop="taxIncludedPrice">
              <el-input v-model="form.taxIncludedPrice" placeholder="请输入含税单价" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="含税金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入金额(元)" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="签证" prop="visa">
              <el-input v-model="form.visa" placeholder="请输入签证" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="劳务供应商" prop="laborSupplier">
              <el-input v-model="form.laborSupplier" placeholder="请输入劳务供应商" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="扣款" prop="deduction">
              <el-input v-model="form.deduction" placeholder="请输入扣款" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="进项税率" prop="taxRate">
              <el-select v-model="form.taxRate" placeholder="请选择进项税率" filterable style="width: 100%">
                <el-option v-for="dict in dict.type.input_tax" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <el-form-item label="签证" prop="visa">
              <el-input v-model="form.visa" placeholder="请输入签证" />
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
        </el-form-item>

        <el-form-item label="上传凭证" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="upload" drag action="#" :auto-upload="true" list-type="picture-card"
              :on-change="onUploadChange" :on-remove="onUploadRemove" :on-exceed="onUploadExceed"
              :file-list="uploadFileList" accept="image/*" class="upload-component" :http-request="handleCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将图片拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅用于随单据上传的图片凭证，支持多张
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="上传文件" class="upload-form-item">
          <div class="upload-container">
            <el-upload ref="fileUpload" drag action="#" :auto-upload="true" list-type="text"
              :on-change="onFileUploadChange" :on-remove="onFileUploadRemove" :on-exceed="onFileUploadExceed"
              :file-list="uploadDocumentList" accept=".pdf,.doc,.docx" class="file-upload-component"
              :http-request="handleFileCustomUpload">
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                仅支持PDF和Word文件，支持多个文件
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 项目劳务台账详情弹窗 -->
    <el-dialog :visible.sync="detailOpen" width="900px" :show-close="true" append-to-body class="daily-detail-dialog">
      <div class="daily-detail-title">项目劳务台账详情</div>
      <div class="daily-section-title">基本信息</div>
      <div class="daily-row-flex">
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">所属项目</th>
              <td class="value">{{ getProjectNameById(detailForm.projectId) }}</td>
            </tr>
            <tr>
              <th class="left-align">开始时间</th>
              <td class="value">{{ parseTime(detailForm.startDate, '{y}-{m}-{d}') }}</td>
            </tr>
            <tr>
              <th class="left-align">截止时间</th>
              <td class="value">{{ parseTime(detailForm.endDate, '{y}-{m}-{d}') }}</td>
            </tr>
            <!-- <tr>
              <th class="left-align">人数</th>
              <td class="value">{{ detailForm.peopleCount }}</td>
            </tr> -->
            <tr>
              <th class="left-align">工种</th>
              <td class="value">{{ detailForm.jobType }}</td>
            </tr>
            <tr>
              <th class="left-align">数量</th>
              <td class="value">{{ detailForm.quantity }}</td>
            </tr>
            <tr>
              <th class="left-align">扣款</th>
              <td class="value">{{ detailForm.deduction }}</td>
            </tr>
            <tr>
              <th class="left-align">签证</th>
              <td class="value">{{ detailForm.visa }}</td>
            </tr>
            <tr>
              <th class="left-align">增值税</th>
              <td class="value">{{ detailForm.vat }}</td>
            </tr>
          </table>
        </div>
        <div class="daily-col-flex">
          <table class="daily-detail-table">
            <tr>
              <th class="left-align">计量单位</th>
              <td class="value">{{ detailForm.unitOfMeasurement }}</td>
            </tr>
            <tr>
              <th class="left-align">含税单价</th>
              <td class="value">{{ detailForm.taxIncludedPrice }}</td>
            </tr>
            <tr>
              <th class="left-align">含税金额</th>
              <td class="value">{{ detailForm.amount }}</td>
            </tr>
            <tr>
              <th class="left-align">不含税金额</th>
              <td class="value">{{ detailForm.taxExcludedCost }}</td>
            </tr>
            <tr>
              <th class="left-align">劳务供应商</th>
              <td class="value">{{ detailForm.laborSupplier }}</td>
            </tr>
            <tr>
              <th class="left-align">进项税率</th>
              <td class="value"><dict-tag :options="dict.type.input_tax" :value="detailForm.taxRate" /></td>
            </tr>
            <tr>
              <th class="left-align">审核状态</th>
              <td class="value"><dict-tag :options="dict.type.review_status" :value="detailForm.auditStatus" /></td>
            </tr>
            <tr>
              <th class="left-align">备注</th>
              <td class="value">{{ detailForm.remark }}</td>
            </tr>
          </table>
        </div>
      </div>
      <!-- 图片展示区域 -->
      <div class="daily-section-title">凭证信息</div>
      <div v-if="detailImageUrls && detailImageUrls.length > 0" class="image-display-container">
        <div v-for="(url, index) in detailImageUrls" :key="`display-${index}`" class="image-item">
          <el-image :src="url" :preview-src-list="detailImageUrls" fit="cover" class="detail-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>

      <!-- 文件展示区域 -->
      <div v-if="detailFileList && detailFileList.length > 0" class="daily-section-title">附件信息</div>
      <div v-if="detailFileList && detailFileList.length > 0" class="file-display-container">
        <div v-for="(file, index) in detailFileList" :key="`file-${index}`" class="file-item">
          <div class="file-info">
            <i class="el-icon-document"></i>
            <span class="file-name">{{ file.fileName }}</span>
            <div class="file-actions">
              <el-button type="primary" size="mini" icon="el-icon-download" @click="handleFileDownload(file)">
                下载
              </el-button>
              <el-button type="success" size="mini" icon="el-icon-view" @click="handleFilePreview(file)">
                预览
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false" type="primary" plain>关闭</el-button>
      </span>
    </el-dialog>

    <!-- 导入弹窗 -->
    <el-dialog title="导入项目劳务台账" :visible.sync="importOpen" width="500px" append-to-body>
      <el-form ref="importForm" :model="importForm" :rules="importRules" label-width="100px">
        <el-form-item label="所属项目" prop="porjectId">
          <el-select v-model="importForm.porjectId" placeholder="请选择所属项目" style="width: 100%">
            <el-option v-for="item in projectOptions" :key="item.id" :label="item.projectName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload ref="upload" :limit="1" accept=".xlsx,.xls" :headers="upload.headers" :action="upload.url"
            :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
            :on-change="handleFileChange" :auto-upload="false" drag>
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip text-center" slot="tip">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false"
                style="font-size:12px;vertical-align: baseline; margin-left: 8px;"
                @click="importTemplate">下载模板</el-link>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitImport" :loading="upload.isUploading">确 定</el-button>
        <el-button @click="cancelImport">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加劳务类型对话框 -->
    <el-dialog title="添加劳务类型" :visible.sync="showAddTypeDialog" width="500px" append-to-body
      @close="addTypeForm.typeName = ''">
      <el-form :model="addTypeForm" @submit.native.prevent>
        <el-form-item label="类型名称" label-width="80px">
          <el-input v-model="addTypeForm.typeName" placeholder="请输入类型名称" @keyup.enter.native.prevent />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddTypeDialog = false">取 消</el-button>
        <el-button type="primary" :loading="addTypeLoading" @click="handleAddType">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 文件预览弹框 -->
    <el-dialog :visible.sync="previewDialogVisible" width="60vw" top="5vh" :title="getPreviewTitle()"
      @close="previewFile = null">
      <div v-if="previewFile">
        <!-- 图片预览 -->
        <el-image v-if="getFileType(previewFile.fileName) === 'image'" :src="previewFile.downloadUrl"
          :preview-src-list="[previewFile.downloadUrl]" fit="contain"
          style="max-width:100%;max-height:70vh;display:block;margin:auto;cursor:pointer;">
          <div slot="error" class="image-slot">
            <i class="el-icon-picture-outline"></i>
          </div>
        </el-image>
        <!-- 文档/PDF/Word/Excel 预览：直接用iframe打开 -->
        <iframe v-else-if="['pdf', 'word', 'excel', 'ppt'].includes(getFileType(previewFile.fileName))"
          :src="previewFile.downloadUrl" style="width:100%;height:70vh;border:none;"></iframe>
        <!-- 其他类型提示 -->
        <div v-else style="text-align:center;padding:40px 0;color:#888;">
          暂不支持该类型文件的在线预览，请下载后查看。
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProdProjectLabor, getProdProjectLabor, delProdProjectLabor, addProdProjectLabor, updateProdProjectLabor, prodProjectLaborFileImport, getAmountTotal } from "@/api/cost/prodProjectLabor";
import { listMaterialLedgerType, addMaterialLedgerType, delMaterialLedgerType } from "@/api/cost/materialLedgerType";
import { listAllProjectContractInfo } from '@/api/production/projectContractInfo';
import { addImg, delImg } from "@/api/cost/materialLedger";
import { fileLinkTransfer, fileLinkLooking } from "@/api/production/projectFileInfo";

export default {
  name: "ProdProjectLabor",
  dicts: ['review_status', 'input_tax'],
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目劳务台账表格数据
      prodProjectLaborList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 台账类型相关
      ledgerTypes: [],
      activeType: '',
      showAddTypeDialog: false,
      addTypeForm: { typeName: '' },
      addTypeLoading: false,
      typeParams: { pageNum: 1, pageSize: 10, typeName: null, remark: null },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        projectId: null,
        startDate: null,
        endDate: null,
        peopleCount: null,
        jobType: null,
        quantity: null,
        unitOfMeasurement: null,
        taxIncludedPrice: null,
        amount: null,
        laborSupplier: null,
        taxRate: null,
        taxExcludedCost: null,
        vat: null,
        remark: null,
        auditStatus: null,
        ledgerTypeId: null,
      },
      // 表单参数
      form: {
        imageList: [], // 存储转换后的图片链接数组
        projectAmountTotal: null, // 项目总含税金额
      },
      // 加载状态
      loadingAmount: false,
      // 详情弹窗
      detailOpen: false,
      detailForm: {},
      // 详情页面的图片链接
      detailImageUrls: [],
      // 详情页面的文件列表
      detailFileList: [],
      // 文件预览相关
      previewDialogVisible: false,
      previewFile: null,
      // 处理后的图片链接（用于回显）
      processedImageList: [],
      // 上传文件列表（图片）
      uploadFileList: [],
      // 上传文件列表（文档）
      uploadDocumentList: [],
      // 项目选项
      projectOptions: [],
      // 导入相关
      importOpen: false,
      importForm: { porjectId: null, file: null },
      importRules: {
        porjectId: [{ required: true, message: "请选择所属项目", trigger: "change" }],
        file: [{ required: true, message: "请选择要导入的文件", trigger: "change" }]
      },
      upload: {
        isUploading: false,
        headers: {},
        url: process.env.VUE_APP_BASE_API + "/common/upload"
      },
      // 表单校验
      rules: {
        projectId: [
          { required: true, message: "所属项目不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "截止时间不能为空", trigger: "blur" }
        ],
        peopleCount: [
          { required: true, message: "人数不能为空", trigger: "blur" }
        ],
        jobType: [
          { required: true, message: "工种不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        unitOfMeasurement: [
          { required: true, message: "计量单位不能为空", trigger: "blur" }
        ],
        taxIncludedPrice: [
          { required: true, message: "含税单价不能为空", trigger: "blur" }
        ],
        amount: [
          { required: true, message: "含税金额不能为空", trigger: "blur" }
        ],
        deduction: [
          { required: true, message: "扣款金额不能为空", trigger: "blur" }
        ],
        laborSupplier: [
          { required: true, message: "劳务供应商不能为空", trigger: "blur" }
        ],
        taxRate: [
          { required: true, message: "进项税率不能为空", trigger: "change" }
        ],
        taxExcludedCost: [
          { required: true, message: "不含税金额不能为空", trigger: "blur" }
        ],
        vat: [
          { required: true, message: "增值税不能为空", trigger: "blur" }
        ],
        visa: [
          { required: true, message: "签证不能为空", trigger: "blur" }
        ],
      }
    };
  },
  async created() {
    await this.fetchProjectOptions();
    await this.getTypeList();
    this.upload.headers = { Authorization: "Bearer " + this.$store.getters.token };
  },
  methods: {
    /** 查询劳务类型列表 */
    async getTypeList() {
      const params = { ...this.typeParams, menuType: 'prodProjectLabor' };
      try {
        const response = await listMaterialLedgerType(params);
        this.ledgerTypes = [];
        (response.rows || []).forEach(item => {
          this.ledgerTypes.push({ label: item.typeName, value: String(item.id), icon: 'el-icon-document' });
        });
        if (this.ledgerTypes.length > 0) {
          this.activeType = this.ledgerTypes[0].value;
          this.queryParams.ledgerTypeId = this.ledgerTypes[0].value;
        } else {
          this.activeType = '';
          this.queryParams.ledgerTypeId = null;
        }
        this.getList();
      } catch (e) {
        this.ledgerTypes = [];
        this.activeType = '';
        this.queryParams.ledgerTypeId = null;
        this.getList();
      }
    },
    /** 查询项目劳务台账列表 */
    getList() {
      this.loading = true;
      listProdProjectLabor(this.queryParams).then(response => {
        // 统一后端返回与前端使用的类型：进项税率统一为字符串
        this.prodProjectLaborList = (response.rows || []).map(item => ({
          ...item,
          taxRate: this.normalizeTaxRate(item.taxRate),
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        projectId: null,
        startDate: null,
        endDate: null,
        peopleCount: null,
        jobType: null,
        quantity: null,
        unitOfMeasurement: null,
        taxIncludedPrice: null,
        amount: null,
        deduction: null,
        laborSupplier: null,
        taxRate: null,
        taxExcludedCost: null,
        vat: null,
        visa: null,
        remark: null,
        auditStatus: 1,
        entryTime: null,
        ledgerTypeId: null,
        imageList: [], // 重置图片链接数组
      };
      this.uploadFileList = [];
      this.uploadDocumentList = []; // 重置文档上传列表
      this.processedImageList = []; // 重置处理后的图片链接
      this.resetForm("form");
    },
    /** 获取项目选项 */
    fetchProjectOptions() {
      listAllProjectContractInfo().then(res => {
        this.projectOptions = res.data || [];
      });
    },
    /** 根据项目ID获取项目名称 */
    getProjectNameById(projectId) {
      const item = this.projectOptions.find(p => p.id == projectId);
      return String(item ? item.projectName : (projectId ?? ''));
    },
    /** 处理项目选择变化 */
    async handleProjectChange(projectId) {
      // 先清空当前值，避免显示上一次的结果
      this.form.projectAmountTotal = null;

      if (!projectId || !this.activeType) {
        return;
      }

      // 显示加载状态
      this.loadingAmount = true;

      try {
        const response = await getAmountTotal(this.activeType, projectId);
        this.form.projectAmountTotal = response.data || 0;
      } catch (error) {
        console.error("获取项目总含税金额失败:", error);
        this.$message.error("获取项目总含税金额失败");
        this.form.projectAmountTotal = null;
      } finally {
        // 无论成功失败都要关闭加载状态
        this.loadingAmount = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      if (this.ledgerTypes && this.ledgerTypes.length > 0) {
        this.activeType = this.ledgerTypes[0].value;
        this.queryParams.ledgerTypeId = this.ledgerTypes[0].value;
      } else {
        this.activeType = '';
        this.queryParams.ledgerTypeId = null;
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      if (!this.activeType) {
        this.$message.warning('请先选择劳务类型');
        return;
      }
      this.reset();
      this.form.ledgerTypeId = this.activeType;
      this.form.entryTime = this.parseTime(new Date());
      this.open = true;
      this.title = "添加项目劳务台账";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      try {
        const response = await getProdProjectLabor(id);
        this.form = response.data;
        // 统一进项税率类型为字符串，便于与字典选项匹配
        this.form.taxRate = this.normalizeTaxRate(this.form.taxRate);

        // 处理图片回显
        await this.processImageListForDisplay();

        this.open = true;
        this.title = "修改项目劳务台账";
      } catch (error) {
        console.error("修改 - 获取数据失败:", error);
        this.$message.error("获取数据失败");
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保进项税率格式统一
          this.form.taxRate = this.normalizeTaxRate(this.form.taxRate);
          if (this.form.id != null) {
            updateProdProjectLabor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            // 新增默认未审核，并自动添加录入时间
            this.form.auditStatus = 1;
            if (!this.form.entryTime) this.form.entryTime = this.parseTime(new Date());
            if (!this.form.ledgerTypeId) this.form.ledgerTypeId = this.activeType;
            addProdProjectLabor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    async handleDetail(row) {
      try {
        const response = await getProdProjectLabor(row.id);
        this.detailForm = response.data || {};
        // 统一详情中进项税率的数据类型为字符串
        this.detailForm.taxRate = this.normalizeTaxRate(this.detailForm.taxRate);

        // 处理图片和文件链接转换
        await this.processDetailImageAndFiles();

        this.detailOpen = true;
      } catch (error) {
        console.error("获取详情失败:", error);
        this.$message.error("获取详情失败");
      }
    },
    handleAudit(row) {
      const data = { ...row, auditStatus: 2, clickAudit: true };
      updateProdProjectLabor(data).then(() => {
        this.$modal.msgSuccess('审核成功');
        this.getList();
      });
    },
    handleCancelAudit(row) {
      const data = { ...row, auditStatus: 1, clickAudit: true };
      updateProdProjectLabor(data).then(() => {
        this.$modal.msgSuccess('已取消审核');
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除？').then(function () {
        return delProdProjectLabor(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('cost/prodProjectLabor/export', {
        ...this.queryParams
      }, `prodProjectLabor_${new Date().getTime()}.xlsx`)
    },
    // 导入：打开/取消/重置
    handleImport() {
      if (!this.activeType) {
        this.$message.warning('请先选择劳务类型');
        return;
      }
      this.importOpen = true;
      this.resetImport();
    },
    cancelImport() {
      this.importOpen = false;
      this.resetImport();
    },
    resetImport() {
      this.importForm = { porjectId: null, file: null };
      if (this.$refs.upload) this.$refs.upload.clearFiles();
      this.resetForm('importForm');
    },
    handleFileUploadProgress() {
      this.upload.isUploading = true;
    },
    handleFileSuccess(response, file) {
      this.upload.isUploading = false;
      this.importForm.file = file;
    },
    handleFileChange(file) {
      this.importForm.file = file;
    },
    submitImport() {
      this.$refs['importForm'].validate(valid => {
        if (!valid) return;
        if (!this.importForm.file && (!this.$refs.upload || !this.$refs.upload.uploadFiles.length)) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        const file = this.importForm.file || (this.$refs.upload ? this.$refs.upload.uploadFiles[0] : null);
        if (!file) {
          this.$modal.msgError('请选择要导入的文件');
          return;
        }
        this.upload.isUploading = true;
        prodProjectLaborFileImport(file, this.importForm.porjectId).then(() => {
          this.$modal.msgSuccess('导入成功');
          this.importOpen = false;
          this.resetImport();
          this.getList();
        }).catch(() => {
          this.upload.isUploading = false;
        });
      });
    },
    importTemplate() {
      const url = 'https://ggkt-1319488159.cos.ap-beijing.myqcloud.com/%E6%88%90%E6%9C%AC%E7%AE%A1%E7%90%86%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88/%E9%A1%B9%E7%9B%AE%E5%8A%B3%E5%8A%A1%E5%8F%B0%E8%B4%A6%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx';
      window.open(url, '_blank');
    },
    /** 表格行样式 */
    rowClassName({ row, rowIndex }) {
      // 只有当审核状态为未审核(1)时才显示颜色
      if (row.auditStatus !== 1) {
        return '';
      }

      // 计算录入时间与截至日期的差值
      const entry = this.parseDate(row.entryTime, true); // 传入true表示是entryTime字段
      const endDate = this.parseDate(row.endDate);

      if (!entry || !endDate) {
        return '';
      }

      const diffDays = Math.floor((entry.getTime() - endDate.getTime()) / 86400000);

      if (diffDays > 7) {
        return 'over-seven-days';
      }
      if (diffDays > 3) {
        return 'over-three-days';
      }
      return '';
    },

    // 兼容多种日期字符串格式的解析，特别处理ISO 8601格式
    parseDate(val, isEntryTime = false) {
      if (!val) return null;
      if (val instanceof Date) return isNaN(val.getTime()) ? null : val;
      if (typeof val === 'string') {
        let s = val.trim();

        // 如果是entryTime字段，只取前面的年月日部分
        if (isEntryTime && s.includes('T')) {
          const dateOnly = s.substring(0, 10); // 截取 "2025-08-11" 部分
          const d = new Date(dateOnly);
          if (!isNaN(d.getTime())) return d;
        }

        // 优先处理ISO 8601格式："2025-08-08T10:53:29.000+08:00"
        if (s.includes('T') && (s.includes('+') || s.includes('Z'))) {
          const d = new Date(s);
          if (!isNaN(d.getTime())) return d;
        }

        // 处理其他格式
        s = s.replace('T', ' ').replace(/-/g, '/');
        const d = new Date(s);
        if (!isNaN(d.getTime())) return d;

        // 退化为仅日期部分
        const onlyDate = s.slice(0, 10);
        const d2 = new Date(onlyDate);
        return isNaN(d2.getTime()) ? null : d2;
      }
      return null;
    },

    // 统一进项税率格式为字符串
    normalizeTaxRate(taxRate) {
      if (taxRate === null || taxRate === undefined) {
        return null;
      }
      return String(taxRate);
    },

    // 检测文本是否被截断
    isTextTruncated(text) {
      if (!text) return false;
      const tempElement = document.createElement('span');
      tempElement.style.cssText = `
        position: absolute;
        visibility: hidden;
        white-space: nowrap;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
        width: auto;
        height: auto;
      `;
      tempElement.textContent = text;
      document.body.appendChild(tempElement);
      const textWidth = tempElement.offsetWidth;
      const containerWidth = 120;
      document.body.removeChild(tempElement);
      return textWidth > containerWidth;
    },

    // 类型选择
    async handleTypeSelect(val) {
      this.activeType = String(val);
      this.queryParams.ledgerTypeId = String(val);
      this.form.ledgerTypeId = String(val);
      await this.getList();
    },
    async handleDeleteType(type) {
      // console.log('handleDeleteType', type, this.prodProjectLaborList);
      const hasData = this.prodProjectLaborList && this.prodProjectLaborList.some(item => item.ledgerTypeId == type.value);
      if (hasData) {
        this.$message.warning('该类型下有台账数据，不能删除！');
        return;
      }
      try {
        await this.$confirm(`是否确认删除劳务类型"${type.label}"？`, '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' });
        await delMaterialLedgerType(type.value);
        this.$message.success('删除成功');
        this.getTypeList();
      } catch (error) { }
    },
    async handleAddType() {
      if (!this.addTypeForm.typeName.trim()) {
        this.$message.warning('请输入类型名称');
        return;
      }
      this.addTypeLoading = true;
      try {
        await addMaterialLedgerType({ typeName: this.addTypeForm.typeName, menuType: 'prodProjectLabor' });
        this.$message.success('添加成功');
        this.showAddTypeDialog = false;
        this.addTypeForm.typeName = '';
        this.getTypeList();
      } catch (error) {
        this.$message.error('添加失败');
      } finally {
        this.addTypeLoading = false;
      }
    },
    // 处理详情页面的图片和文件
    async processDetailImageAndFiles() {
      if (!this.detailForm.imageList?.length) {
        this.detailImageUrls = [];
        this.detailFileList = [];
        return;
      }

      this.detailImageUrls = [];
      this.detailFileList = [];

      for (let i = 0; i < this.detailForm.imageList.length; i++) {
        const url = this.detailForm.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件
            this.detailImageUrls.push(displayUrl);
          } else {
            // 文档文件
            this.detailFileList.push({
              fileName: fileName,
              downloadUrl: url,
              displayUrl: displayUrl,
              fileType: fileType
            });
          }
        } catch (error) {
          console.error(`处理文件失败:`, error);
        }
      }
    },
    // 获取文件类型
    getFileType(fileName) {
      if (!fileName) return 'unknown';
      const extension = fileName.split('.').pop().toLowerCase();
      const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
      const pdfTypes = ['pdf'];
      const wordTypes = ['doc', 'docx'];
      const excelTypes = ['xls', 'xlsx'];
      const pptTypes = ['ppt', 'pptx'];

      if (imageTypes.includes(extension)) return 'image';
      if (pdfTypes.includes(extension)) return 'pdf';
      if (wordTypes.includes(extension)) return 'word';
      if (excelTypes.includes(extension)) return 'excel';
      if (pptTypes.includes(extension)) return 'ppt';
      return 'unknown';
    },
    // 判断是否为图片文件
    isImageFile(fileType) {
      return fileType === 'image';
    },
    // 从URL中提取文件名
    getFileNameFromUrl(url) {
      if (!url) return 'unknown';
      const parts = url.split('/');
      return parts[parts.length - 1] || 'unknown';
    },
    // 文件下载
    async handleFileDownload(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的下载链接");
        return;
      }
      try {
        const res = await fileLinkTransfer(file.downloadUrl);
        const newUrl = res.data.url;
        if (!newUrl) {
          this.$message.error("获取下载链接失败");
          return;
        }
        // 创建a标签下载
        const a = document.createElement("a");
        a.href = newUrl;
        a.download = file.fileName || "";
        a.target = "_blank";
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
      } catch (e) {
        this.$message.error("下载失败");
      }
    },
    // 文件预览
    async handleFilePreview(file) {
      if (!file.downloadUrl) {
        this.$message.error("无效的预览链接");
        return;
      }
      try {
        let newUrl = '';
        const fileType = this.getFileType(file.fileName);

        if (fileType === 'image') {
          // 图片直接使用fileLinkTransfer
          const res = await fileLinkTransfer(file.downloadUrl);
          newUrl = res.data.url;
        } else if (['pdf', 'word', 'excel', 'ppt'].includes(fileType)) {
          // 文档使用fileLinkLooking
          const res = await fileLinkLooking(file.downloadUrl);
          newUrl = res.data.url;
        } else {
          newUrl = file.downloadUrl;
        }

        if (!newUrl) {
          this.$message.error("获取预览链接失败");
          return;
        }

        this.previewFile = { ...file, downloadUrl: newUrl };
        this.previewDialogVisible = true;
      } catch (e) {
        this.$message.error("预览失败");
      }
    },
    // 获取预览标题
    getPreviewTitle() {
      if (this.previewFile && this.previewFile.fileName) {
        return this.previewFile.fileName;
      }
      return "文件预览";
    },
    // 上传相关方法
    onUploadChange(file, fileList) {
      this.uploadFileList = fileList;
    },
    // 自定义上传：调用 addImg 接口将文件转为图片链接
    async handleCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的图片链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "image.jpg",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadFileList = [...this.uploadFileList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("图片上传失败");
        param?.onError?.(err);
      }
    },
    // 删除图片：仅本地移除，不调用后端
    async onUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadFileList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadFileList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadFileList = fileList;
    },
    onUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 张图片，已选择 ${files.length} 张`
      );
    },
    // 文件上传相关方法
    onFileUploadChange(file, fileList) {
      this.uploadDocumentList = fileList;
    },
    // 自定义文件上传：调用 addImg 接口将文件转为文件链接
    async handleFileCustomUpload(param) {
      const { file } = param || {};
      if (!file) {
        param?.onError?.(new Error("无可上传文件"));
        return;
      }

      // 检查文件类型
      const allowedTypes = ['.pdf', '.doc', '.docx'];
      const fileExtension = '.' + file.name.split('.').pop().toLowerCase();
      if (!allowedTypes.includes(fileExtension)) {
        this.$message.error("只支持PDF和Word文件");
        param?.onError?.(new Error("文件类型不支持"));
        return;
      }

      try {
        // 上传文件并获取原始路径
        const { msg: filePath } = await addImg(file);
        if (!filePath) {
          throw new Error("未获取到文件路径");
        }

        // 获取可访问链接
        const {
          data: { url },
        } = await fileLinkTransfer(filePath);
        if (!url) {
          throw new Error("未获取到可访问的文件链接");
        }

        // 创建文件项，保存原始路径用于删除
        const fileItem = {
          name: file.name || "document.pdf",
          url,
          uid: file.uid?.toString() || Date.now().toString(),
          originalPath: filePath, // 保存原始路径
        };

        // 更新文件列表和表单数据
        this.uploadDocumentList = [...this.uploadDocumentList, fileItem];
        this.form.imageList.push(filePath);

        // 调用成功回调
        param?.onSuccess?.({ url });
      } catch (err) {
        this.$message.error("文件上传失败");
        param?.onError?.(err);
      }
    },
    // 删除文件：仅本地移除，不调用后端
    async onFileUploadRemove(file, fileList) {
      const { url } = file || {};
      if (!url) {
        this.uploadDocumentList = fileList;
        return;
      }

      // 找到对应的文件项，获取原始路径，仅更新本地数组
      const fileItem = this.uploadDocumentList.find((item) => item.url === url);
      if (fileItem && fileItem.originalPath) {
        const originalPath = fileItem.originalPath;
        const imageListIndex = this.form.imageList.indexOf(originalPath);
        if (imageListIndex > -1) {
          this.form.imageList.splice(imageListIndex, 1);
        }
      }
      this.uploadDocumentList = fileList;
    },
    onFileUploadExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 ${fileList.length} 个文件，已选择 ${files.length} 个`
      );
    },
    // 获取可访问的图片链接（用于显示）
    async getDisplayImageUrl(url) {
      if (!url) {
        return "";
      }

      try {
        const {
          data: { url: accessibleUrl },
        } = await fileLinkTransfer(url);
        return accessibleUrl || url;
      } catch (error) {
        console.error("getDisplayImageUrl - 转换失败:", error);
        return url;
      }
    },
    // 处理图片列表用于显示
    async processImageListForDisplay() {
      if (!this.form.imageList?.length) {
        this.form.imageList = [];
        this.uploadFileList = [];
        this.uploadDocumentList = [];
        return;
      }

      this.uploadFileList = [];
      this.uploadDocumentList = [];

      for (let i = 0; i < this.form.imageList.length; i++) {
        const url = this.form.imageList[i];
        try {
          const displayUrl = await this.getDisplayImageUrl(url);
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            // 图片文件，添加到图片上传列表，保存原始路径用于删除
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url: displayUrl,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            // 文档文件，添加到文件上传列表，保存原始路径用于删除
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url: displayUrl,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        } catch (error) {
          console.error(`processImageListForDisplay - 转换失败:`, error);
          // 转换失败时，根据文件名判断类型
          const fileName = this.getFileNameFromUrl(url);
          const fileType = this.getFileType(fileName);

          if (this.isImageFile(fileType)) {
            this.uploadFileList.push({
              name: fileName || `image_${i + 1}.jpg`,
              url,
              uid: `existing_image_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          } else {
            this.uploadDocumentList.push({
              name: fileName || `document_${i + 1}`,
              url,
              uid: `existing_file_${i}`,
              originalPath: url, // 保存原始路径（imageList中的路径）
            });
          }
        }
      }
    },
  }
};
</script>

<style lang="scss" scoped>
.el-menu {
  border-right: none;
}

.app-container {
  height: calc(100vh - 140px);
  overflow: auto;
  box-sizing: border-box;
  padding-bottom: 24px;
}

::v-deep .el-menu-item {
  position: relative;
}

.type-delete-icon {
  display: none;
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.el-menu-item:hover .type-delete-icon {
  display: inline-block;
}

::v-deep .el-menu-item {
  padding-left: 0 !important;
  padding-right: 0 !important;
  width: 100%;
  box-sizing: border-box;
}

::v-deep .el-card__body {
  padding: 8px !important;
}

.custom-menu-item {
  display: flex !important;
  align-items: center;
  position: relative;
  padding-right: 8px;
}

.item-icon {
  margin-right: 0;
  flex-shrink: 0;
}

.item-title-tooltip {
  flex: 1 1 120px;
  max-width: 120px;
  min-width: 0;
  margin-right: 8px;
}

.item-title {
  display: inline-block;
  width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  vertical-align: middle;
}

.type-delete-icon {
  color: #F56C6C;
  padding: 0;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
  margin-left: 8px;
}

.custom-menu-item:hover .type-delete-icon {
  opacity: 1;
}

.ledger-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.ledger-detail-title {
  font-size: 24px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 24px;
  text-align: center;
  letter-spacing: 2px;
}

.ledger-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 24px 0 12px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.ledger-row-flex {
  display: flex;
  gap: 32px;
}

.ledger-col-flex {
  flex: 1;
}

.ledger-detail-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 12px;
}

.ledger-detail-table th,
.ledger-detail-table td {
  padding: 6px 12px;
  border-bottom: 1px solid #eaeaea;
}

.ledger-detail-table th.left-align {
  text-align: left;
  background: #f7f7fa;
  width: 120px;
}

.ledger-detail-table td.value {
  color: #333;
}

/* 表格行样式 */
::v-deep .el-table .over-three-days>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table .over-seven-days>td {
  background-color: #f8d7da !important;
}

/* 去掉表格鼠标移入时的默认背景变色效果 */
::v-deep .el-table__body tr:hover>td {
  background-color: transparent !important;
}

::v-deep .el-table__body tr.over-three-days:hover>td {
  background-color: #fff3cd !important;
}

::v-deep .el-table__body tr.over-seven-days:hover>td {
  background-color: #f8d7da !important;
}

/* 颜色图例样式 */
.color-legend {
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
  border: 1px solid #e9ecef;
}

.color-legend span {
  display: inline-flex;
  align-items: center;
  margin-right: 20px;
}

.color-legend span:last-child {
  margin-right: 0;
}

.daily-detail-dialog .el-dialog__body {
  background: #f4f6fb;
  padding: 0;
}

.daily-detail-title {
  font-size: 28px;
  font-weight: bold;
  color: #2d3a4b;
  margin-bottom: 36px;
  text-align: center;
  letter-spacing: 2px;
}

.daily-section-title {
  font-size: 18px;
  color: #4a90e2;
  font-weight: bold;
  margin: 32px 0 16px 0;
  border-left: 4px solid #4a90e2;
  padding-left: 12px;
  letter-spacing: 1px;
}

.daily-row-flex {
  display: flex;
  gap: 32px;
  margin-bottom: 12px;
}

.daily-col-flex {
  flex: 1;
}

.daily-detail-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0;
  background: none;
}

.daily-detail-table th,
.daily-detail-table td {
  padding: 10px 8px;
  font-size: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.daily-detail-table th {
  width: 120px;
  color: #6b7a90;
  background: none;
  font-weight: normal;
  text-align: right;
  vertical-align: top;
  padding-right: 12px;
}

.daily-detail-table td.value {
  color: #222;
  text-align: left;
  font-weight: 500;
}

.daily-detail-table tr:last-child td,
.daily-detail-table tr:last-child th {
  border-bottom: none;
}

@media (max-width: 900px) {
  .daily-row-flex {
    flex-direction: column;
    gap: 0;
  }
}

@media (max-width: 600px) {
  .daily-detail-title {
    font-size: 20px;
  }

  .daily-section-title {
    font-size: 15px;
    padding-left: 8px;
  }

  .daily-detail-table th,
  .daily-detail-table td {
    font-size: 13px;
    padding: 7px 4px;
  }
}

.amount-value {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
  margin-right: 8px;
}

.amount-unit {
  font-size: 14px;
  color: #666;
}

.amount-loading {
  color: #409EFF;
  font-size: 14px;
}

/* 上传组件样式 */
.upload-container {
  width: 100%;
  overflow: hidden;
  margin-bottom: 10px;
}

.upload-component {
  width: 100%;
}

/* 上传表单项样式 */
.upload-form-item {
  margin-bottom: 20px;
}

.upload-form-item .el-form-item__content {
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload--picture-card {
  width: 120px;
  height: 120px;
  line-height: 118px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  width: 120px;
  height: 120px;
}

::v-deep .upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
}

::v-deep .upload-component .el-upload-list--picture-card {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: 8px;
  margin-bottom: 10px;
}

::v-deep .upload-component .el-upload-list--picture-card .el-upload-list__item {
  margin: 0;
}

/* 确保上传组件在对话框内不会溢出 */
::v-deep .el-dialog__body .upload-container {
  max-width: 100%;
  box-sizing: border-box;
}

/* 统一上传组件样式，避免双重边框 */
::v-deep .upload-component .el-upload-dragger {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
}

::v-deep .upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

/* 调整对话框底部按钮区域的上边距 */
::v-deep .el-dialog__footer {
  padding-top: 20px;
  border-top: 1px solid #e4e7ed;
}

/* 文件上传组件样式 */
.file-upload-component {
  width: 100%;
}

.file-upload-component .el-upload-dragger {
  width: 100%;
  height: 120px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  text-align: center;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
}

.file-upload-component .el-upload-dragger:hover {
  border-color: #409eff;
}

.file-upload-component .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
  margin-top: 8px;
}

.file-upload-component .el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.file-upload-component .el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

/* 文件列表样式 */
.file-upload-component .el-upload-list--text {
  margin-top: 8px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item {
  background-color: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 8px 12px;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-name {
  color: #606266;
  font-size: 14px;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-status-label {
  color: #67c23a;
  font-size: 12px;
}

.file-upload-component .el-upload-list--text .el-upload-list__item-delete {
  color: #f56c6c;
  cursor: pointer;
  font-size: 16px;
}

/* 详情弹窗图片展示样式 */
.image-display-container {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin: 16px 0;
}

.image-item {
  width: 120px;
  height: 120px;
  border-radius: 6px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.detail-image {
  width: 100%;
  height: 100%;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 20px;
}

/* 文件展示区域样式 */
.file-display-container {
  margin: 16px 0;
}

.file-item {
  margin-bottom: 12px;
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  transition: all 0.2s;
}

.file-item:hover {
  background: #e9ecef;
  border-color: #409eff;
}

.file-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.file-info i {
  color: #409eff;
  font-size: 18px;
  margin-right: 8px;
}

.file-name {
  flex: 1;
  color: #333;
  font-size: 14px;
  margin-right: 12px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

/* 项目总金额显示区域样式 */
.amount-display-section {
  background: transparent;
  border: none;
  padding: 0;
  margin: 0 0 20px 0;
  display: flex;
  align-items: center;
}

.amount-display-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  margin-right: 8px;
}

.amount-display-content {
  display: flex;
  align-items: center;
}

.amount-loading {
  color: #409eff;
  font-size: 14px;
}

.amount-value {
  font-size: 16px;
  font-weight: bold;
  color: #409eff;
}

.amount-unit {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
}
</style>
